//
//  RspCacheDAO.m
//  GBNetWork
//
//  Created by chenguibang on 16/2/29.
//  Copyright © 2016年 Chen. All rights reserved.
//

#import "RspCacheDAO.h"
#import "RspCache.h"

@implementation RspCacheDAO
-(BOOL)insert:(RspCacheModel*)model{
    NSManagedObjectContext *cxt = [self managedObjectContext];
    RspCache *insertmodel =(RspCache*)[NSEntityDescription insertNewObjectForEntityForName:@"RspCache" inManagedObjectContext:cxt];
    insertmodel.requrlstr = model.requrlstr;
    insertmodel.rspdata  = model.rspdata;
    NSError *error = nil;
    if ([self.managedObjectContext save:&error]) {
        NSLog(@"数据插入成功");
        return YES;
    }else{
        NSLog(@"数据插入失败");
        return NO;
    }
    return NO;
}

-(RspCacheModel *)findById:(RspCacheModel *)model{
    NSManagedObjectContext *cxt = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"RspCache" inManagedObjectContext:cxt];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setEntity:entityDescription];
    
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"requrlstr = %@",model.requrlstr];
    [request setPredicate:predicte];
    
    NSError *error = nil;
    NSArray *listdata = [cxt executeFetchRequest:request error:&error];
    
    if ([listdata count]>0) {
        RspCache *ca = [listdata lastObject];
        RspCacheModel *rs = [[RspCacheModel alloc]init];
        rs.requrlstr = ca.requrlstr;
        rs.rspdata = ca.rspdata;
        return rs;
    }
    return nil;
}
-(void)clearAllCache{
    NSManagedObjectContext *cxt = [self managedObjectContext];
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"RspCache" inManagedObjectContext:cxt];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setEntity:entityDescription];
    NSError *error = nil;
    NSArray *listdata = [cxt executeFetchRequest:request error:&error];
    for (NSManagedObject *obj in listdata) {
        [cxt deleteObject:obj];
        NSError *error = nil;
        if ([cxt save:&error]) {
            NSLog(@"删除成功");
        }else{
            NSLog(@"失败");
        }
    }
}
@end
